
package net.alpcontrol.bi.bootstrap.utils;

import com.alibaba.fastjson.JSONObject;
import net.alpcontrol.bi.bootstrap.exception.AlpException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class AlpNetUtils {
    private static final String CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded;charset=UTF-8";
    private static final String CONTENT_TYPE_JSON = "application/json;charset=UTF-8";

    public AlpNetUtils() {
    }

    public static OutputStream getOutputStream(HttpServletResponse response) {
        ServletOutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return outputStream;
    }

    public static String getRequestOrigin(HttpServletRequest request) {
        String origin = request.getHeader("origin");
        origin = AlpStringUtils.trimToNull(origin);
        if(origin == null) {
            origin = request.getHeader("referer");
            origin = AlpStringUtils.trimToNull(origin);
        }

        return origin;
    }

    public static String getHeaders(HttpServletRequest request) {
        Enumeration<String> names = request.getHeaderNames();
        StringBuffer sbContent = new StringBuffer();

        while(names.hasMoreElements()) {
            String name = (String)names.nextElement();
            sbContent.append(name).append("=").append(request.getHeader(name)).append("\r\n");
        }

        return sbContent.toString();
    }

    private static boolean validIpAddress(String ip) {
        String trimIp = StringUtils.trimToNull(ip);
        return trimIp == null?false:!"unknown".equalsIgnoreCase(ip);
    }

    public static String getIpAddress2(HttpServletRequest request) {
        String ipAddr = request.getHeader("x-forwarded-for");
        if(validIpAddress(ipAddr)) {
            return ipAddr;
        } else {
            ipAddr = request.getHeader("Proxy-Client-IP");
            if(validIpAddress(ipAddr)) {
                return ipAddr;
            } else {
                ipAddr = request.getHeader("WL-Proxy-Client-IP");
                if(validIpAddress(ipAddr)) {
                    return ipAddr;
                } else {
                    ipAddr = request.getRemoteAddr();
                    if(validIpAddress(ipAddr)) {
                        return ipAddr;
                    } else {
                        ipAddr = request.getHeader("http_client_ip");
                        if(validIpAddress(ipAddr)) {
                            return ipAddr;
                        } else {
                            ipAddr = request.getHeader("HTTP_X_FORWARDED_FOR");
                            if(ipAddr != null && ipAddr.indexOf(",") != -1) {
                                ipAddr = ipAddr.substring(ipAddr.lastIndexOf(",") + 1, ipAddr.length()).trim();
                            }

                            return ipAddr;
                        }
                    }
                }
            }
        }
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ipAddr = request.getHeader("x-forwarded-for");
        if(ipAddr == null || ipAddr.length() == 0 || "unknown".equalsIgnoreCase(ipAddr)) {
            ipAddr = request.getHeader("Proxy-Client-IP");
        }

        if(ipAddr == null || ipAddr.length() == 0 || "unknown".equalsIgnoreCase(ipAddr)) {
            ipAddr = request.getHeader("WL-Proxy-Client-IP");
        }

        if(ipAddr == null || ipAddr.length() == 0 || "unknown".equalsIgnoreCase(ipAddr)) {
            ipAddr = request.getRemoteAddr();
            if(ipAddr.equals("127.0.0.1") || ipAddr.equals("0:0:0:0:0:0:0:1")) {
                InetAddress inet = null;

                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException var7) {
                    var7.printStackTrace();
                }

                ipAddr = inet.getHostAddress();
            }
        }

        if(ipAddr != null && ipAddr.length() > 0) {
            String[] ipAddrs = ipAddr.split(",");
            String[] var3 = ipAddrs;
            int var4 = ipAddrs.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String addr = var3[var5];
                if(!"unknown".equalsIgnoreCase(addr)) {
                    ipAddr = addr;
                    break;
                }
            }
        }

        return ipAddr;
    }

    public static void writeJson(HttpServletResponse response, Object object) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;

        try {
            writer = response.getWriter();
            writer.print(JSONObject.toJSONString(object));
            writer.flush();
        } catch (IOException var7) {
            var7.printStackTrace();
        } finally {
            if(writer != null) {
                writer.close();
            }

        }

    }

    public static Map<String, String> getParameters(HttpServletRequest request) {
        Map properties = request.getParameterMap();
        Map result = new HashMap();
        Iterator entries = properties.entrySet().iterator();

        String name;
        for(String value = ""; entries.hasNext(); result.put(name, value)) {
            Entry entry = (Entry)entries.next();
            name = (String)entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj) {
                value = "";
            } else if(!(valueObj instanceof String[])) {
                value = valueObj.toString();
            } else {
                String[] values = (String[])((String[])valueObj);

                for(int i = 0; i < values.length; ++i) {
                    value = values[i] + ",";
                }

                value = value.substring(0, value.length() - 1);
            }
        }

        return result;
    }

    public static String getUrlParameters(HttpServletRequest request) {
        StringBuffer sbParameters = new StringBuffer();

        String key;
        String value;
        for(Enumeration names = request.getParameterNames(); names.hasMoreElements(); sbParameters.append(key).append("=").append(value)) {
            key = (String)names.nextElement();
            String[] values = request.getParameterValues(key);
            value = "";
            String[] var6 = values;
            int var7 = values.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                String item = var6[var8];
                if(value.equals("")) {
                    value = value + item;
                } else {
                    value = value + "&" + item;
                }
            }

            if(sbParameters.length() > 0) {
                sbParameters.append("&");
            }
        }

        return sbParameters.toString();
    }

    public String getUrlContent(String url) {
        HttpURLConnection conn = null;
        InputStream inStream = null;
        BufferedReader reader = null;
        StringBuffer sbContent = new StringBuffer();

        try {
            URL requestUrl = new URL(url);
            conn = (HttpURLConnection)requestUrl.openConnection();
            conn.setRequestProperty("Content-type", "text/html");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.connect();
            inStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));

            String line;
            while((line = reader.readLine()) != null) {
                sbContent.append(line);
            }
        } catch (Exception var11) {
            var11.printStackTrace();
        } finally {
            closeBufferedReader(reader);
            closeInputStream(inStream);
            disconnectHttpConnection(conn);
        }

        return sbContent.toString();
    }

    public static String getRequestUrl(HttpServletRequest request) {
        String requestUrl = String.format("%s://%s:%d%s%s", new Object[]{request.getScheme(), request.getServerName(), Integer.valueOf(request.getServerPort()), request.getContextPath(), request.getServletPath()});
        String params = request.getQueryString();
        if(!StringUtils.isBlank(params)) {
            requestUrl = requestUrl + "?" + params;
        }

        return requestUrl;
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                if(name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }

        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Cookie[] var4 = cookies;
            int var5 = cookies.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Cookie cookie = var4[var6];
                if(cookie.getName().equals(name)) {
                    value = cookie.getValue();
                    break;
                }
            }
        }

        return value;
    }

    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge, String domainName) {
        Cookie cookie = new Cookie(name, value);
        cookie.setSecure(false);
        cookie.setMaxAge(maxAge < 0?-1:maxAge);
        if(domainName != null) {
            cookie.setDomain(domainName);
        }

        cookie.setPath("/");
        cookie.setVersion(-1);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name, String domainName) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Cookie[] var5 = cookies;
            int var6 = cookies.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                Cookie cookie = var5[var7];
                if(cookie.getName().equals(name)) {
                    cookie.setValue((String)null);
                    cookie.setMaxAge(0);
                    if(domainName != null) {
                        cookie.setDomain(domainName);
                    }

                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }

    }

    public static <T> T getAppContextBean(HttpServletRequest request, Class<T> type) {
        Object obj = request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        WebApplicationContext context = (WebApplicationContext)obj;
        return context == null?null:context.getBean(type);
    }

    public static <T> T getAppContextBean(Class<T> type) {
        WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
        ServletContext sc = context.getServletContext();
        return WebApplicationContextUtils.getRequiredWebApplicationContext(sc).getBean(type);
    }

    public static <T> T getAppContextBean(String name) {
        WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
        ServletContext sc = context.getServletContext();
        return (T) WebApplicationContextUtils.getRequiredWebApplicationContext(sc).getBean(name);
    }

    public static HttpServletRequest getServletRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs == null?null:attrs.getRequest();
    }

    public static HttpServletResponse getServletResponse() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return (new ServletWebRequest(request)).getResponse();
    }

    public static String getBaseUrl(HttpServletRequest request) {
        StringBuffer sbBaseUrl = new StringBuffer();
        sbBaseUrl.append(request.getScheme()).append("://").append(request.getServerName());
        if(request.getServerPort() != 80) {
            sbBaseUrl.append(":").append(request.getServerPort());
        }

        sbBaseUrl.append(request.getContextPath());
        return sbBaseUrl.toString();
    }

    public static int getSimplePlatform() {
        return "/".equals(File.separator)?2:("\\".equals(File.separator)?3:1);
    }

    public static String getRootPath() {
        int platform = getSimplePlatform();
        if(platform == 1) {
            return null;
        } else {
            String classPath = AlpNetUtils.class.getResource("HHNetUtils.class").toString();

            String result;
            try {
                result = URLDecoder.decode(classPath, "utf-8");
            } catch (Exception var4) {
                result = null;
            }

            if(AlpStringUtils.isNullOrEmpty(result)) {
                return null;
            } else {
                int index = result.indexOf("WEB-INF");
                if(index == -1) {
                    index = result.indexOf("bin");
                    if(index == -1) {
                        return null;
                    }
                }

                result = result.substring(0, index);
                if(result.startsWith("jar")) {
                    result = result.substring(platform == 3?10:9);
                } else if(result.startsWith("file")) {
                    result = result.substring(platform == 3?6:5);
                }

                if(result.endsWith("/")) {
                    result = result.substring(0, result.length() - 1);
                }

                return result;
            }
        }
    }

    public static String getWebPath() {
        int platform = getSimplePlatform();
        if(platform == 1) {
            return null;
        } else {
            String classPath = AlpNetUtils.class.getResource("HHNetUtils.class").toString();

            String result;
            try {
                result = URLDecoder.decode(classPath, "utf-8");
            } catch (Exception var4) {
                result = null;
            }

            if(AlpStringUtils.isNullOrEmpty(result)) {
                return null;
            } else {
                int index = result.indexOf("WEB-INF");
                if(index == -1) {
                    return null;
                } else {
                    result = result.substring(0, index + 7);
                    if(result.startsWith("jar")) {
                        result = result.substring(platform == 3?10:9);
                    } else if(result.startsWith("file")) {
                        result = result.substring(platform == 3?6:5);
                    }

                    if(result.endsWith("/")) {
                        result = result.substring(0, result.length() - 1);
                    }

                    return result;
                }
            }
        }
    }

    public static boolean isAdjaxJsonRequest(HttpServletRequest request) {
        String header;
        return request == null?false:((header = request.getHeader("accept")) == null?false:(header.indexOf("application/json") >= 0?true:((header = request.getHeader("X-Requested-With")) == null?false:header.indexOf("XMLHttpRequest") >= 0)));
    }

    public static String appendUrlParameter(String url, String name, String value) {
        String link = url.indexOf("?") >= 0?"&":"?";
        StringBuffer sbUrl = new StringBuffer();
        return sbUrl.append(url).append(link).append(name).append("=").append(value).toString();
    }

    public static String appendUrlPortions(String url, String... portions) {
        String trimUrl = AlpStringUtils.trimToNull(url);
        if(trimUrl == null) {
            return null;
        } else if(portions != null && portions.length > 0) {
            StringBuffer sbResult = new StringBuffer(trimUrl);
            String[] var4 = portions;
            int var5 = portions.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String portion = var4[var6];
                String trimPortion = StringUtils.trimToNull(portion);
                if(trimPortion != null) {
                    if(trimUrl.charAt(trimUrl.length() - 1) == 47) {
                        if(trimPortion.charAt(0) == 47) {
                            sbResult.append(trimPortion.substring(1));
                        } else {
                            sbResult.append(trimPortion);
                        }
                    } else if(trimPortion.charAt(0) == 47) {
                        sbResult.append(trimPortion);
                    } else {
                        sbResult.append("/").append(trimPortion);
                    }
                }
            }

            return sbResult.toString();
        } else {
            return trimUrl;
        }
    }

    public static void sendRedirect(HttpServletResponse response, String url) {
        try {
            response.sendRedirect(url);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }

    public static String httpGet(String url, String contentType) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;

        String result;
        try {
            connection = (HttpURLConnection)(new URL(url)).openConnection();
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setRequestMethod("GET");
            connection.setAllowUserInteraction(false);
            inputStream = connection.getInputStream();
            result = IOUtils.toString(inputStream, "UTF-8");
        } catch (Exception var9) {
            result = null;
            throw new AlpException(var9.getMessage());
        } finally {
            closeInputStream(inputStream);
            disconnectHttpConnection(connection);
        }

        return result;
    }

    public static String httpGetJson(String url) {
        return httpGet(url, "application/json;charset=UTF-8");
    }

    public static String httpGetForm(String url) {
        return httpGet(url, "application/x-www-form-urlencoded;charset=UTF-8");
    }

    public static String httpPost(String url, String content, String contentType) {
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        OutputStreamWriter writer = null;
        InputStream inputStream = null;

        String result;
        try {
            connection = (HttpURLConnection)(new URL(url)).openConnection();
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setAllowUserInteraction(false);
            if(!AlpStringUtils.isNullOrEmpty(content)) {
                outputStream = connection.getOutputStream();
                writer = new OutputStreamWriter(outputStream, "UTF-8");
                writer.write(content);
                writer.flush();
                outputStream.flush();
            }

            inputStream = connection.getInputStream();
            result = IOUtils.toString(inputStream, "UTF-8");
        } catch (Exception var12) {
            result = null;
            throw new AlpException(var12.getMessage());
        } finally {
            closeOutputStream(outputStream);
            closeOutputStreamWriter(writer);
            closeInputStream(inputStream);
            disconnectHttpConnection(connection);
        }

        return result;
    }

    public static String httpPostJson(String url, Map<String, String> keyValues) {
        StringBuffer sbContent = null;
        if(keyValues != null && keyValues.size() > 0) {
            sbContent = new StringBuffer();
            Iterator<Entry<String, String>> iter = keyValues.entrySet().iterator();
            sbContent.append("{");

            for(; iter.hasNext(); sbContent.append("\",")) {
                Entry<String, String> entry = (Entry)iter.next();
                sbContent.append("\"").append((String)entry.getKey()).append("\":\"");
                if(entry.getKey() != null) {
                    sbContent.append((String)entry.getValue());
                }
            }

            sbContent.setLength(sbContent.length() - 1);
            sbContent.append("}");
        }

        return httpPost(url, sbContent.toString(), "application/json;charset=UTF-8");
    }

    public static String httpPostJson(String url, String json) {
        return httpPost(url, json, "application/json;charset=UTF-8");
    }

    public static String httpPostForm(String url, Map<String, String> keyValues) {
        StringBuffer sbContent = null;
        if(keyValues != null && keyValues.size() > 0) {
            sbContent = new StringBuffer();

            for(Iterator iter = keyValues.entrySet().iterator(); iter.hasNext(); sbContent.append("&")) {
                Entry<String, String> entry = (Entry)iter.next();
                sbContent.append((String)entry.getKey()).append("=");
                if(entry.getValue() != null) {
                    sbContent.append((String)entry.getValue());
                }
            }

            sbContent.setLength(sbContent.length() - 1);
        }

        return httpPost(url, sbContent.toString(), "application/x-www-form-urlencoded;charset=UTF-8");
    }

    public static void closeInputStream(InputStream stream) {
        if(stream != null) {
            try {
                stream.close();
            } catch (IOException var2) {
                var2.printStackTrace();
            }
        }

    }

    public static void closeOutputStream(OutputStream stream) {
        if(stream != null) {
            try {
                stream.close();
            } catch (IOException var2) {
                var2.printStackTrace();
            }
        }

    }

    public static void closeBufferedReader(BufferedReader reader) {
        if(reader != null) {
            try {
                reader.close();
            } catch (IOException var2) {
                var2.printStackTrace();
            }
        }

    }

    public static void closeOutputStreamWriter(OutputStreamWriter writer) {
        if(writer != null) {
            try {
                writer.close();
            } catch (IOException var2) {
                var2.printStackTrace();
            }
        }

    }

    public static void disconnectHttpConnection(HttpURLConnection connection) {
        if(connection != null) {
            connection.disconnect();
        }

    }
}
